
import 'dart:io';

import 'package:confuse_util/controller/zys_input_controller.dart';
import 'package:confuse_util/view/zys_input.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';

import '../util/excel_reader.dart';


class MyHomePage extends StatelessWidget {

  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  Widget build(BuildContext context) {
    Get.lazyPut(() => ZysInputController());
    final controller = Get.find<ZysInputController>();
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () async {
                FilePickerResult? result = await FilePicker.platform.pickFiles(
                  type: FileType.custom,
                  allowedExtensions: ['csv'],
                  allowMultiple: false,
                );
                if (result != null) {
                  File file = File(result.files.single.path!);
                  List<ExcelData> csv = await ExcelReader.readCsvFile(file.path);
                  List<List<String?>> httpStringList = (ExcelReader.findHttp(csv.first, "balo"));
                  if(httpStringList.length == 0) {
                    SmartDialog.showToast("没找到");
                  } else if (httpStringList.length == 1) {

                    controller.appHttp.value = httpStringList.first[0]!;
                    controller.useHttp.value = httpStringList.first[1]!;
                    controller.wssHttp.value = httpStringList.first[2]!;
                    controller.logHttp.value = httpStringList.first[3]!;
                    SmartDialog.showToast("读取成功");
                  } else {
                    SmartDialog.showToast("存在多个结果，请选择");
                  }
                } else {
                  // User canceled the picker
                }
              },
              child: Text("选择CSV"),
            ),
            Obx(() => ZysInput(labText: "test-app", bodyText: controller.appHttp.value,)),
            Obx(() => ZysInput(labText: "app-正式域名", bodyText: controller.useHttp.value,)),
            Obx(() => ZysInput(labText: "test-wss", bodyText: controller.wssHttp.value,)),
            Obx(() => ZysInput(labText: "test-log", bodyText: controller.logHttp.value,)),
          ],
        ),
      ),
    );
  }
}